<template>
    <div class="playground">
        <canvas ref="canvas" @contextmenu.prevent></canvas>
        
        <!-- 引入公共游戏组件 -->
        <GameComponents
            :isPaused="isPaused"
            :gameOver="gameOver"
            :gameWon="gameWon"
            :resultMessage="resultMessage"
            :showExitConfirm="showExitConfirm"
            :remainingTime="remainingTime"
            @pause="togglePause"
            @resume="resumeGame"
            @restart="handleRestart"
            @exit="handleExit"
            @simulateCompletion="simulateCompletion"
            @closeExitConfirm="showExitConfirm = $event"
        />
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, defineProps, defineEmits } from 'vue';
import { SingleMap } from '@/assets/scripts/single/SingleMap';
import { GameObject } from '@/assets/scripts/GameObject';
import GameComponents from '@/components/GameComponents.vue';

const props = defineProps({
    level: {
        type: String,
        default: 'third'
    }
});

const emit = defineEmits(['complete']);

// 游戏状态
const canvas = ref(null);
const gameMap = ref(null);
const gameOver = ref(false);
const gameWon = ref(false);
const resultMessage = ref('');
const remainingTime = ref(60); // 60秒倒计时
const timerInterval = ref(null);
const isPaused = ref(false); // 游戏是否暂停
const showExitConfirm = ref(false); // 是否显示退出确认

// 启动倒计时
const startTimer = () => {
    clearInterval(timerInterval.value);
    remainingTime.value = 60;
    
    timerInterval.value = setInterval(() => {
        // 仅在游戏未暂停时更新时间
        if (!isPaused.value) {
            remainingTime.value--;
            
            if (remainingTime.value <= 0) {
                clearInterval(timerInterval.value);
                handleTimeUp();
            }
        }
    }, 1000);
};

// 时间用尽处理
const handleTimeUp = () => {
    if (!gameOver.value) {
        gameOver.value = true;
        gameWon.value = false;
        resultMessage.value = '时间到！你未能在规定时间内消灭所有敌人。';
    }
};

// 游戏结束处理
const handleGameOver = (won) => {
    gameOver.value = true;
    gameWon.value = won;
    clearInterval(timerInterval.value);
    
    if (won) {
        resultMessage.value = '恭喜你击败了所有敌人！';
    } else {
        resultMessage.value = '你被敌人击败了，再接再厉！';
    }
};

// 玩家死亡处理
const handlePlayerDeath = (player) => {
    // 此方法在玩家死亡时会被游戏地图调用
    console.log('玩家死亡:', player.info.role);
};

// 模拟完成游戏
const simulateCompletion = () => {
    handleGameOver(true);
};

// 暂停游戏
const togglePause = () => {
    isPaused.value = !isPaused.value;
    if (isPaused.value) {
        GameObject.pause_game();
    } else {
        GameObject.resume_game();
    }
};

// 继续游戏
const resumeGame = () => {
    isPaused.value = false;
    GameObject.resume_game();
};

// 重新开始游戏
const handleRestart = () => {
    cleanupGame();
    gameOver.value = false;
    gameWon.value = false;
    resultMessage.value = '';
    isPaused.value = false;
    showExitConfirm.value = false;
    initGame();
};

// 退出游戏
const handleExit = () => {
    cleanupGame();
    showExitConfirm.value = false;
    isPaused.value = false;
    emit('complete');
};

// 初始化游戏
const initGame = () => {
    if (!canvas.value) return;
    
    const ctx = canvas.value.getContext('2d');
    
    // 调整画布大小
    const resizeCanvas = () => {
        const parent = canvas.value.parentElement;
        canvas.value.width = parent.clientWidth;
        canvas.value.height = parent.clientHeight;
    };
    
    // 初始化画布大小
    resizeCanvas();
    
    // 创建游戏地图实例，使用third难度级别
    gameMap.value = new SingleMap(ctx, 'third');
    
    // 设置游戏事件回调
    gameMap.value.setEventCallback('onGameOver', handleGameOver);
    gameMap.value.setEventCallback('onPlayerDeath', handlePlayerDeath);
    
    // 开始游戏循环
    gameMap.value.start();
    
    // 添加窗口大小变化监听
    window.addEventListener('resize', resizeCanvas);
    
    // 添加键盘事件监听
    window.addEventListener('keydown', handleKeyDown);
    
    // 启动游戏帧循环
    const gameLoop = () => {
        if (gameMap.value && !gameOver.value && !isPaused.value) {
            gameMap.value.update();
            requestAnimationFrame(gameLoop);
        } else if (!gameOver.value) {
            // 如果暂停但未结束，继续请求下一帧以便在恢复时立即继续
            requestAnimationFrame(gameLoop);
        }
    };
    
    // 启动游戏循环
    gameLoop();
    
    // 启动倒计时
    startTimer();
};

// 处理键盘事件
const handleKeyDown = (event) => {
    // Esc键暂停/恢复游戏
    if (event.key === 'Escape') {
        // 如果显示退出确认，则先关闭
        if (showExitConfirm.value) {
            showExitConfirm.value = false;
            return;
        }
        
        // 如果游戏已结束，不响应暂停
        if (gameOver.value) {
            return;
        }
        
        togglePause();
    }
};

// 清理游戏资源
const cleanupGame = () => {
    clearInterval(timerInterval.value);
    
    // 移除事件监听
    window.removeEventListener('resize', () => {});
    window.removeEventListener('keydown', handleKeyDown);
    
    // 使用GameObject的静态方法清理所有游戏对象
    if (typeof GameObject.clearAll === 'function') {
        GameObject.clearAll();
    }
    
    // 清理游戏地图
    gameMap.value = null;
};

// 监听props变化
watch(() => props.level, (newLevel) => {
    console.log('关卡变化:', newLevel);
    if (newLevel) {
        handleRestart();
    }
});

// 组件挂载
onMounted(() => {
    initGame();
});

// 组件卸载
onUnmounted(() => {
    cleanupGame();
});
</script>

<style scoped>
.playground {
    width: 100%;
    height: 100%;
    position: relative;
    overflow: hidden;
    background-color: #111;
}

canvas {
    width: 100%;
    height: 100%;
    display: block;
}
</style>
